import { Injectable, Inject, BadRequestException } from '@nestjs/common'
import { CreateRelationDto } from './dto/create-relation.dto'
import { UpdateRelationDto } from './dto/update-relation.dto'
import { Repository } from 'typeorm'
import { Relation } from './entities/relation.entity'

@Injectable()
export class RelationService {

  constructor(
    @Inject('RELATION_REPOSITORY')
    private readonly relationRepository: Repository<Relation>
  ) { }

  async create(createRelationDto: CreateRelationDto) {
    let res = undefined
    try {
      res = await this.relationRepository.insert(createRelationDto)
    } catch (error) {
      throw new BadRequestException("插入关系数据错误：" + error)
    }
    return res
  }

  async findAll() {
    let res = undefined
    try {
      res = await this.relationRepository.findAndCount()
    } catch (error) {
      throw new BadRequestException("查找关系数据错误：" + error)
    }
    return res
  }

  async findOne(id: number) {
    let res = undefined
    try {
      res = await this.relationRepository.findOne({ rid: id })
    } catch (error) {
      throw new BadRequestException("查找关系数据错误：" + error)
    }
    return res
  }

  async update(id: number, updateModeDto: UpdateRelationDto) {
    let res = undefined
    try {
      res = await this.relationRepository.update({ rid: id }, updateModeDto)
    } catch (error) {
      throw new BadRequestException("更新关系数据错误：" + error)
    }
    return res
  }

  async remove(id: number) {
    let res = undefined
    try {
      res = await this.relationRepository.delete({ rid: id })
    } catch (error) {
      throw new BadRequestException("删除关系数据错误：" + error)
    }
    return res
  }
}
